package com.xj.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * @Description: MD5 工具类
 * @Author: Chuanlei.Sun
 * @Date: Created in 2018/10/28 23:30
 */
@Slf4j
public final class MD5Utils {


    /**
     * 加密字符串
     *
     * @param plainText 字符串
     * @return java.lang.String
     * @author Chuanlei.Sun
     * @date 2018/10/28 23:30
     */
    public static String encode(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuilder buf = new StringBuilder("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            log.trace("32位的加密:{} ", buf.toString());
            log.trace("16位的加密:{} ", buf.toString().substring(8, 24));
            return buf.toString();
        } catch (Exception e) {
            log.error("加密异常: ", e);
        }
        return "";
    }

    /**
     * 文件加密
     *
     * @param filePath 文件路径
     * @return java.lang.String
     * @author Chuanlei.Sun
     * @date 2018/10/28 23:34
     */
    public static String getFileMD5(String filePath) {
        String value = null;
        FileInputStream in = null;
        try {
            File file = new File(filePath);
            in = new FileInputStream(file);
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int c;
            while ((c = in.read(buffer)) != -1) {
                md5.update(buffer, 0, c);
            }
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16).toUpperCase();
        } catch (Exception e) {
            log.error("文件加密异常：", e);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("文件加密异常：", e);
                }
            }
        }
        return value;
    }
}
